from flask import Flask, render_template, request, redirect, url_for
import mysql.connector

app = Flask(__name__)

# 数据库连接函数
def connect_to_db():
    try:
        connection = mysql.connector.connect(
            host='localhost',
            user='root',
            password='123456',
            database='tss'
        )
        if connection.is_connected():
            print("成功连接到数据库")
        return connection
    except mysql.connector.Error as err:
        print(f"数据库连接错误: {err}")
        return None

# 首页路由
@app.route('/')
def index():
    return render_template('index.html')

# 选择目的地页面
@app.route('/select_destination', methods=['GET', 'POST'])
def select_destination():
    if request.method == 'POST':
        destination = request.form['destination']
        if destination:
            return redirect(url_for('select_ticket', destination=destination))
        else:
            return render_template('select_ticket.html', error="请输入有效的目的地代码！")
    return render_template('select_destination.html')

# 选择车票类型页面
@app.route('/select_ticket', methods=['GET', 'POST'])
def select_ticket():
    destination = request.args.get('destination')
    if request.method == 'POST':
        ticket_type = request.form['ticket_type']
        return redirect(url_for('select_payment', destination=destination, ticket_type=ticket_type))
    return render_template('select_ticket.html', destination=destination)

# 选择支付方式页面
@app.route('/select_payment', methods=['GET', 'POST'])
def select_payment():
    destination = request.args.get('destination')
    ticket_type = request.args.get('ticket_type')
    if request.method == 'POST':
        payment_method = request.form['payment_method']
        # 保存到数据库
        save_transaction_to_db(destination, ticket_type, payment_method)
        return redirect(url_for('success', destination=destination, ticket_type=ticket_type, payment_method=payment_method))
    return render_template('payment.html', destination=destination, ticket_type=ticket_type)

# 支付成功页面
@app.route('/success')
def success():
    destination = request.args.get('destination')
    ticket_type = request.args.get('ticket_type')
    payment_method = request.args.get('payment_method')
    return render_template('success.html', destination=destination, ticket_type=ticket_type, payment_method=payment_method)

# 保存交易信息到数据库
def save_transaction_to_db(destination, ticket_type, payment_method):
    connection = connect_to_db()
    if connection:
        cursor = connection.cursor()
        query = "INSERT INTO transactions (destination, ticket_type, payment_method) VALUES (%s, %s, %s)"
        values = (destination, ticket_type, payment_method)
        cursor.execute(query, values)
        connection.commit()
        cursor.close()
        connection.close()

if __name__ == '__main__':
    app.run(debug=True)
